/*
 * Copyright (c) 2011-2024, Cpjit (cpjit@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cpjit.data.web;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortArgumentResolver;
import org.springframework.data.web.SortHandlerMethodArgumentResolver;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * MyBatisPlus 分页参数解析器
 *
 * @author yonhuan
 */
@Setter
@Slf4j
public class MyBatisPlusPageHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private static final String DEFAULT_PAGE_PARAMETER = "page";
    private static final String DEFAULT_SIZE_PARAMETER = "size";
    private static final SortHandlerMethodArgumentResolver DEFAULT_SORT_RESOLVER = new SortHandlerMethodArgumentResolver();
    private String pageParameterName = DEFAULT_PAGE_PARAMETER;
    private String sizeParameterName = DEFAULT_SIZE_PARAMETER;
    private int defaultPageSize = 20;
    private boolean oneIndexedParameters = false;
    private SortArgumentResolver sortResolver = DEFAULT_SORT_RESOLVER;


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return IPage.class.equals(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Page<?> page = new Page<>();
        String pageNumber = webRequest.getParameter(pageParameterName);
        if (StringUtils.isNotBlank(pageNumber)) {
            page.setCurrent(Long.parseLong(pageNumber));
        } else {
            page.setCurrent(oneIndexedParameters ? 1 : 0);
        }
        String pageSize = webRequest.getParameter(sizeParameterName);
        if (StringUtils.isNotBlank(pageSize)) {
            page.setSize(Long.parseLong(pageSize));
        } else {
            page.setSize(defaultPageSize);
        }
        Sort sort = sortResolver.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);
        List<OrderItem> orderItems = sort.stream()
                .map(order -> parseOrderItem((Class<?>) ((ParameterizedType) methodParameter.getParameter().getParameterizedType()).getActualTypeArguments()[0], order))
                .filter(Objects::nonNull)
                .toList();
        page.setOrders(orderItems);
        return page;
    }

    final static OrderItem parseOrderItem(Class<?> clazz, Sort.Order order) {
        Field field = ReflectionUtils.findField(clazz, order.getProperty());
        if (field == null) {
            if (log.isDebugEnabled()) {
                log.debug("无效的排序字段 {}#{}", clazz.getName(), order.getProperty());
            }
            return null;
        }
        String columnName = getColumnName(clazz, field);
        return order.isAscending() ? OrderItem.asc(columnName) : OrderItem.desc(columnName);
    }

    /**
     * 获取Java字段对应的数据库列名
     */
    private static String getColumnName(Class<?> clazz, Field field) {
        return Optional.ofNullable(TableInfoHelper.getTableInfo(clazz))
                .stream()
                .flatMap(t -> t.getFieldList().stream())
                .filter(f -> f.getField().equals(field))
                .findFirst()
                .map(TableFieldInfo::getColumn)
                // 无法通过mybatis-plus获取到字段的列名的时候
                .orElseGet(() -> getColumnName(field));
    }

    private static String getColumnName(Field field) {
        TableField tableField = field.getAnnotation(TableField.class);
        String columnName = null;
        if (tableField != null) {
            columnName = tableField.value();
        }
        if (StringUtils.isBlank(columnName)) {
            columnName = StrUtil.toUnderlineCase(field.getName());
        }
        return columnName;
    }
}
